﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Entity;
using BAL;
using Common;
using System.Text;
using System.Data;
namespace Web
{
    public partial class PostStudentScore : System.Web.UI.Page
    {
        private int examid = 0;
        private int editid = 0;
        private int delid = 0;
        private string page = "1";
        private static UserLinkExtendInfo Uinfo = new UserLinkExtendInfo();
        private IList<ExamRoomInfo> examroomInfos = new List<ExamRoomInfo>();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!UserValidate.CheckLogin(this.Request, "InputScore"))
            {
                Response.Write("<script type=\"text/javascript\">top.location.href='login.aspx';</script>");
                Response.Redirect("login.aspx");
                Response.End();
            }
            if (!PageValidate.QueryStringIsEmpty("examid"))
            {
                examid = int.Parse(PageValidate.QueryString("examid"));
            }
            if (!PageValidate.QueryStringIsEmpty("editid"))
            {
                editid = int.Parse(PageValidate.QueryString("editid"));
            }
            if (!PageValidate.QueryStringIsEmpty("delid"))
            {
                delid = int.Parse(PageValidate.QueryString("delid"));
            }
            if (!PageValidate.QueryStringIsEmpty("page"))
            {
                page = PageValidate.QueryString("page");
            }
            Uinfo = UserValidate.GetInfo(this.Request);
            if (!IsPostBack)
            {
                if (delid > 0)
                {
                    StudentScoreExtendInfo studentscoreextendInfo = StudentScoreExtend.GetSingleInfo(delid);
                    if (studentscoreextendInfo.UserId != Uinfo.Id)
                    {
                        Utility.ShowJsAlertAndRedirect("DisplayScore.aspx?examid=" + studentscoreextendInfo.ExamRoomId.ToString(), "没有权限对此进于修改！", this);
                        return;
                    }
                    else
                    {
                        StudentScore.DelInfo(delid);
                        Response.Redirect("DisplayScore.aspx?examid=" + examid);
                    }
                }
                if (editid > 0)
                {
                    StudentScoreExtendInfo studentscoreextendInfo = StudentScoreExtend.GetSingleInfo(editid);
                    if (studentscoreextendInfo.UserId != Uinfo.Id)
                    {
                        Utility.ShowJsAlertAndRedirect("DisplayScore.aspx?examid=" + studentscoreextendInfo.ExamRoomId.ToString(), "没有权限对此进于修改！", this);
                        return;
                    }
                    else
                    {
                        this.SelectStudent.Checked = true;
                        this.NewStudent.Enabled = false;
                        examid = studentscoreextendInfo.ExamRoomId;
                        BindExamRoom();
                        BindGrade(studentscoreextendInfo.GradeId);
                        BindClass(studentscoreextendInfo.ClassId);
                        BindStudent(studentscoreextendInfo.StudentId);
                        BindQuestion(ScoreHelper.GetScoreList(studentscoreextendInfo.QuestItemScore));
                    }
                    
                }
                else
                {
                    BindExamRoom();
                    if (this.ExamRoomList.SelectedIndex > -1)
                    {
                        BindGrade(0);
                    }
                    else
                    {
                        Utility.ShowJsAlertAndHistoryBack("您所在的学校还没有年级信息！", this);
                        return;
                    }
                    if (this.GradeList.SelectedIndex > -1)
                    {
                        BindClass(0);
                    }
                    else
                    {
                        Utility.ShowJsAlertAndHistoryBack("您所在的学校还没有班级信息！", this);
                        return;
                    }
                    BindStudent(0);
                    BindQuestion(null);
                    BindSubjectType();
                    BindSourceType();
                }
                
            }
            if (Request.QueryString["post"] != null)
            {
                Utility.ShowBoxyAlert("添加成功，请继续", this);
            }
        }
        protected void BindExamRoom()
        {
            if (examid <= 0)
            {
                examroomInfos = ExamRoom.GetList();
            }
            else
            {
                examroomInfos.Add(ExamRoom.GetSingleInfo(examid));
            }
            foreach (ExamRoomInfo info in examroomInfos)
            {
                ExamRoomList.Items.Add(new ListItem(info.ExamName, info.Id.ToString()));
            }
        }
        protected void BindGrade(int gid)
        {
            IList<GradeInfo> gradeInfos = new List<GradeInfo>();
            gradeInfos = Grade.GetGradeInfoBySchoolId(Uinfo.SchoolId);
            foreach (GradeInfo info in gradeInfos)
            {
                ListItem item = new ListItem();
                item.Text = info.Name;
                item.Value = info.Id.ToString();
                item.Selected = info.Id == gid ? true : false;
                GradeList.Items.Add(item);
            }
        }

        protected void BindClass(int cid)
        {
            IList<TClassInfo> classInfos = new List<TClassInfo>();
            classInfos = TClass.GetClassInfoByGradeId(int.Parse(GradeList.SelectedValue));
            ClassList.Items.Add(new ListItem("请选择班级", "0"));
            foreach (TClassInfo info in classInfos)
            {
                ListItem item = new ListItem();
                item.Text = info.Name;
                item.Value = info.Id.ToString();
                item.Selected = info.Id == cid ? true : false;
                ClassList.Items.Add(item);
            }
        }
        private void BindSubjectType()
        {
            DataTable subTable = new DataTable();
            subTable.Columns.Add("displayMember");
            subTable.Columns.Add("valueMember");
            foreach (SubjectTypes subjecttype in Enum.GetValues(typeof(SubjectTypes)))
            {
                DataRow dr = subTable.NewRow();
                dr["displayMember"] = subjecttype.ToString();
                dr["valueMember"] = (int)subjecttype;
                subTable.Rows.Add(dr);
            }
            this.subjectType.DataSource = subTable;
            this.subjectType.DataTextField = "displayMember";
            this.subjectType.DataValueField = "valueMember";
            this.subjectType.DataBind();
        }

        private void BindSourceType()
        {
            DataTable srcTable = new DataTable();
            srcTable.Columns.Add("displayMember");
            srcTable.Columns.Add("valueMember");
            foreach (SourceTypes sourcetype in Enum.GetValues(typeof(SourceTypes)))
            {
                DataRow dr = srcTable.NewRow();
                dr["displayMember"] = sourcetype.ToString();
                dr["valueMember"] = (int)sourcetype;
                srcTable.Rows.Add(dr);
            }
            this.sourceType.DataSource = srcTable;
            this.sourceType.DataTextField = "displayMember";
            this.sourceType.DataValueField = "valueMember";
            this.sourceType.DataBind();
        }
        protected void BindStudent(int sid)
        {
            if (ClassList.SelectedIndex > 0)
            {
                IList<StudentInfo> studentInfos = new List<StudentInfo>();
                studentInfos = Student.GetListByClassId(int.Parse(ClassList.SelectedValue));
                foreach (StudentInfo info in studentInfos)
                {
                    ListItem item = new ListItem();
                    item.Text = info.Name;
                    item.Value = info.Id.ToString();
                    item.Selected = info.Id == sid ? true : false;
                    StudentList.Items.Add(item);
                }
            }
        }

        protected void BindQuestion(IList<ScoreInfo> scoreInfos)
        {
            string[] hanzi = new string[] { "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十", "二十一", "二十二", "二十三", "二十四", "二十五", "二十六", "二十七", "二十八", "二十九", "三十" };
            IList<PaperQuestionInfo> infos = new List<PaperQuestionInfo>();
            int examPaperId = examroomInfos.Where(e => e.Id == int.Parse(ExamRoomList.SelectedValue)).Select(e => e.ExamPaperId).First();
            if (examPaperId > 0)
            {
                ExamPaperInfo examPaperInfo = BAL.ExamPaper.GetT1(examPaperId);
                infos = Question.GetList(examPaperInfo.Id);
                if (examPaperInfo.TestPaperPolicyMainId == null)
                {
                    examPaperInfo.TestPaperPolicyMainId = 0;
                }
                IList<TestPaperPolicySubInfo> tpinfo = TestPaperPolicySub.GetList((int)examPaperInfo.TestPaperPolicyMainId);
                StringBuilder sb = new StringBuilder();
                int i = 0;
                int a = 1;
                foreach (TestPaperPolicySubInfo info in tpinfo)
                {
                    XmlQuestion xq = XmlQuestionHelper.GetXmlQuestionInfo(info.Content);
                    sb.Append("<li class='title'>");
                    sb.Append(hanzi[i]);
                    sb.Append("、");
                    sb.Append(QuesType.GetQuesTypeInfoById(int.Parse(xq.Type)).Name);
                    sb.Append("共 ");
                    sb.Append(xq.AllCount.ToString());
                    sb.Append(" 小题 ");
                    if (xq.SingleScore != null && xq.SingleScore.Count > 0)
                    {
                        sb.Append("每小题 ");
                        sb.Append(string.Join(",", ArrayHelper.ConvertToStringArray(GetArray<decimal>.Get(xq.SingleScore))));
                        sb.Append(" 分");
                    }
                    sb.Append("总分为：");
                    sb.Append(xq.AllScore.ToString());
                    sb.Append("分");
                    sb.Append("</li>");

                    IList<PaperQuestionInfo> tInfos = infos.Where(t => t.SubPolicyId == info.Id).ToList();
                    foreach (PaperQuestionInfo qinfo in tInfos)
                    {
                        string s = "", v = "";
                        if (scoreInfos != null)
                        {
                            ScoreInfo scoreInfo = scoreInfos.Single(t => t.Id == qinfo.Id);
                            if (scoreInfo != null)
                            {
                                s = scoreInfo.Score;
                                v = scoreInfo.Answer;
                            }
                        }
                        sb.Append("<li class='item'><em>");
                        sb.Append(a.ToString());
                        sb.Append(". </em>得分：");
                        sb.Append("<input type='text' size='5' id='Score" + qinfo.Id + "' name='Score" + qinfo.Id + "' value='" + s + "' onkeyup='clearNoNum(this)'/>");
                        sb.Append("<span class='Answer'>答案：");
                        sb.Append("<input type='text' size='5' id='Answer" + qinfo.Id + "' name='Answer" + qinfo.Id + "' value='" + v + "'/>");
                        sb.Append("</span>");
                        sb.Append("</li>");
                        a++;
                    }
                    sb.Append("<li class='cls'></li>");
                    i++;
                }
                TempList.Text = sb.ToString();
            }
        }
        protected void ExamRoomList_SelectedIndexChanged(object sender, EventArgs e)
        {
            TempList.Text = "";
            if (ExamRoomList.SelectedIndex > -1)
            {
                BindQuestion(null);
            }
        }

        protected void GradeList_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClassList.Items.Clear();
            if (GradeList.SelectedIndex > -1)
            {
                BindClass(0);
            }
        }
        protected void ClassList_SelectedIndexChanged(object sender, EventArgs e)
        {
            StudentList.Items.Clear();
            if (ClassList.SelectedIndex > -1)
            {
                BindStudent(0);
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (!NewStudent.Checked && !SelectStudent.Checked)
            {
                Utility.ShowJsAlert("没有选择学员信息方式！", this);
                return;
            }
            if (ClassList.SelectedValue == "0")
            {
                Utility.ShowJsAlert("没有选择学员所在班级！", this);
                return;
            }
            StudentInfo studentInfo = null;
            if (NewStudent.Checked)
            {
                if (PageValidate.IsEmpty(StuName.Text))
                {
                    Utility.ShowJsAlert("新建学员姓名不能为空！", this);
                    return;
                }
                if (PageValidate.IsEmpty(StuNumber.Text))
                {
                    Utility.ShowJsAlert("新建学员学号不能为空！", this);
                    return;
                }
                studentInfo = new StudentInfo();
                studentInfo.Name = StuName.Text.Trim();
                studentInfo.Number = StuNumber.Text.Trim();
                studentInfo.AreaId = School.GetSingleInfo(Uinfo.SchoolId).AreaId;
                studentInfo.SchoolId = Uinfo.SchoolId;
                studentInfo.GradeId = int.Parse(GradeList.SelectedValue);
                studentInfo.ClassId = int.Parse(ClassList.SelectedValue);
                studentInfo.Sex = Sex0.Checked ? 0 : 1;
                studentInfo.SubjectType = int.Parse(this.subjectType.SelectedValue);
                studentInfo.SourceType = int.Parse(this.sourceType.SelectedValue);
                studentInfo = Student.Save(studentInfo);
            }
            else
            {
                string selectStudentId = CheckBoxListHelper.SelectedValue(StudentList);
                if (PageValidate.IsEmpty(selectStudentId))
                {
                    Utility.ShowJsAlert("没有选择学生信息！", this);
                    return;
                }
                studentInfo = Student.GetSingleInfo(int.Parse(selectStudentId));
            }
            int examRoomId = int.Parse(ExamRoomList.SelectedValue);
            ExamRoomInfo examRoomInfo = ExamRoom.GetSingleInfo(examRoomId);
            ExamPaperInfo examPaperInfo = BAL.ExamPaper.GetT1(examRoomInfo.ExamPaperId);
            IList<PaperQuestionInfo> questionInfos = Question.GetList(examPaperInfo.Id);
            StudentScoreInfo studentScoreInfo = null;
            if (editid > 0)
            {
                studentScoreInfo = StudentScore.GetSingleInfo(editid);

            }
            else
            {
                studentScoreInfo = new StudentScoreInfo();
            }
            studentScoreInfo.UserId = Uinfo.Id;
            studentScoreInfo.ExamRoomId = examRoomId;
            studentScoreInfo.ExamPaperId = examPaperInfo.Id;
            studentScoreInfo.ExamPaperScore = examPaperInfo.Score != null ? decimal.Parse(examPaperInfo.Score.Value.ToString()) : 0;
            studentScoreInfo.SubjectId = examRoomInfo.SubjectId;
            studentScoreInfo.StudentId = studentInfo.Id;
            decimal allscroe = 0;
            StringBuilder sb = new StringBuilder();
            sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            sb.Append("<Questions>");
            foreach (PaperQuestionInfo info in questionInfos)
            {
                string score = "0";
                string answer = "";

                if (!PageValidate.FormIsEmpty("Score" + info.Id))
                {
                    score = PageValidate.Form("Score" + info.Id);
                }
                if (!PageValidate.FormIsEmpty("Answer" + info.Id))
                {
                    answer = PageValidate.Form("Answer" + info.Id);
                }
                try
                {
                    allscroe += decimal.Parse(score);
                }
                catch { }
                sb.Append("<Question>");
                sb.Append("<Id>");
                sb.Append(info.Id);
                sb.Append("</Id>");
                sb.Append("<Score>");
                sb.Append(score);
                sb.Append("</Score>");
                sb.Append("<Answer>");
                sb.Append("<![CDATA[" + answer + "]]>");
                sb.Append("</Answer>");
                sb.Append("</Question>");
            }
            sb.Append("</Questions>");
            studentScoreInfo.CountScore = allscroe;
            studentScoreInfo.QuestItemScore = sb.ToString();
            StudentScore.Save(studentScoreInfo);

            if (editid > 0)
            {
                Utility.ShowJsAlertAndRedirect("DisplayScore.aspx?examid=" + this.ExamRoomList.SelectedValue, "修改成功！", this);
            }
            else
            {
                Utility.ShowJsAlertAndRedirect("PostStudentScore.aspx?examid=" + this.ExamRoomList.SelectedValue, "添加成功！", this);
            }
        }
    }
}
